/**
 * 
 */
package info.niwota.commons.acl;

import android.text.TextUtils;


/**
 * @author qiangli
 *
 */
public final class AccessControl {

	public static final int ACCESS_MASTER = 1;

	public static final int ACCESS_NONE = 0;

	public static final int ACCESS_PUBLIC = 3;

	public static final int ACCESS_SHARED = 2;
	
	public static final int ACCESS_LEVEL_DEFAULT = ACCESS_SHARED;
	
	public static final int ACCESS_PERM_DEFAULT = ACCESS_MASTER;
	
	public static final String S_ACCESS_MASTER = "1";

	public static final String S_ACCESS_NONE = "0";

	public static final String S_ACCESS_PUBLIC = "3";

	public static final String S_ACCESS_SHARED = "2";

	public AccessControl() {
	}

	public static int perm(String perm) {
		try {
			int p = Integer.parseInt(perm);
			return perm(p);
		} catch (Exception e) {
			//
		}
		return ACCESS_MASTER;
	}
	
	public static int perm(int perm) {
		return (perm > 3 || perm < 0) ? ACCESS_MASTER : perm;
	}
	
	/**
	 * Verify authorization of the label. Label is a grouping of resources
	 * denoted by uri's such as folder for file system, frames (E*Frame app),
	 * group for contacts...
	 * 
	 * @param group
	 * @param user
	 * @param label
	 * @return
	 */
	public static boolean canAccess(int group, String user, String label, String perm, String emails) {

		int p = (TextUtils.isEmpty(perm) ? ACCESS_MASTER
				: Integer.parseInt(perm));
		//
		if (p == ACCESS_PUBLIC) {
			return true;
		}
		//
		if (p == ACCESS_NONE) {
			return false;
		}
		//
		if (group == ACCESS_MASTER) {
			return true;
		}
		//
		if (p == ACCESS_MASTER) {
			return false;
		}
		//
		if (p == ACCESS_SHARED
				&& group == ACCESS_PUBLIC) {
			return false;
		}
		if (p == ACCESS_SHARED && !canShare(user, emails)) {
			return false;
		}
		return true;
	}
	
	/**
	 * Check user against the authorized list.
	 * 
	 * @param user
	 * @param emails
	 * @return
	 */
	public static boolean canShare(String user, String emails) {
		if (TextUtils.isEmpty(emails)) {
			return false;
		}
		String[] sa = emails.split(",");
		for (int i = 0; i < sa.length; i++) {
			if (sa[i].equalsIgnoreCase(user)) {
				return true;
			}
		}
		return false;
	}

}
